package com.sds.system.servlets;

import com.estontorise.gae_filestore.interfaces.DataStoreFile;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.sds.system.SystemConstants;
import com.sds.system.services.FileManager;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Logger;

@Singleton
public class FileServlet extends HttpServlet implements SystemConstants {

    private Logger logger = Logger.getLogger(getClass().getName());
    private FileManager fileManager;

    @Inject
    public FileServlet(FileManager fileManager) {
        this.fileManager = fileManager;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            logger.info("Loading file:" + req.getPathInfo());
            resp.setContentType("text/plain");
            resp.setCharacterEncoding("UTF-8");
            DataStoreFile dsf = fileManager.getFile(req.getPathInfo());
            IOUtils.copy(dsf.openForRead(), resp.getOutputStream());
        } catch (IOException ex) {
            logger.warning("[" + ex.getClass().getName() + "]" + ex.getMessage());
            resp.sendError(404);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            if (req.getParameter("content") != null) {
                String userName = req.getParameter("user");
                String password = req.getParameter("pass");
                if (StringUtils.equals(userName, FILE_ADMIN_USERNAME) && StringUtils.equals(password, FILE_ADMIN_PASSWORD)) {
                    logger.info("Writing to file:" + req.getPathInfo());
                    DataStoreFile dsf = fileManager.getFile(req.getPathInfo());
                    OutputStream stream = dsf.openForWrite();
                    IOUtils.write(req.getParameter("content"), stream, "UTF-8");
                    stream.close();
                    resp.getWriter().write("File saved!");
                } else {
                    resp.getWriter().write("Invalid username or password");
                    logger.warning("Unauthorized access from " + req.getRemoteAddr());
                }
            }
        } catch (Exception ex) {
            logger.warning("[" + ex.getClass().getName() + "]" + ex.getMessage());
            resp.sendError(404);
        }
    }
}
